import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 静态内部类实现单例
 */
public class SingleTonStatic {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException, ClassNotFoundException {
//        Constructor<SingleTonStaticTest> sin = SingleTonStaticTest.class.getDeclaredConstructor();
//        sin.setAccessible(true);
//        SingleTonStaticTest singleTonStaticTest = sin.newInstance();
//        SingleTonStaticTest instance = SingleTonStaticTest.getInstance();
//        System.out.println(singleTonStaticTest == instance);

        SingleTonStaticTest instance = SingleTonStaticTest.getInstance();

//        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test"));
//        oos.writeObject(instance);
//        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test"));
        SingleTonStaticTest singleTonStaticTest = ((SingleTonStaticTest) ois.readObject());
        System.out.println(instance == singleTonStaticTest);


    }
}
class SingleTonStaticTest implements Serializable {
    static final long serialVersionUID = 42L;
    //静态内部类
    private static class SingleTon{
        private static SingleTonStaticTest singleTonStaticTest = new SingleTonStaticTest();
    }
    private SingleTonStaticTest(){
        //解决反射创建单例对象的问题
        if (SingleTon.singleTonStaticTest!=null){
            throw new RuntimeException("单例模式不允许创建多个对象");
        }
    }
    public static SingleTonStaticTest getInstance(){
        return SingleTon.singleTonStaticTest;
    }
    Object readResolve() throws ObjectStreamException{
        return SingleTon.singleTonStaticTest;
    }
}
